import { Component, sp } from "cc";
import { _decorator } from "cc";

const { ccclass, property } = _decorator;
@ccclass
export default class SpinePreviewMode extends Component {
    static spinePreviewMode() {
        if (CC_EDITOR) {
            // 重写update方法 达到在编辑模式下 自动播放动画的功能
            sp.Skeleton.prototype['update'] = function (dt) {
                if (CC_EDITOR) {
                    // ['engine']._animatingInEditMode = 1;
                    // ['engine'].animatingInEditMode = 1;
                }
                if (this.paused) return;
                dt *= this.timeScale * sp['timeScale'];
                if (this.isAnimationCached()) {
                    // Cache mode and has animation queue.
                    if (this._isAniComplete) {
                        if (this._animationQueue.length === 0 && !this._headAniInfo) {
                            let frameCache = this._frameCache;
                            if (frameCache && frameCache.isInvalid()) {
                                frameCache.updateToFrame();
                                let frames = frameCache.frames;
                                this._curFrame = frames[frames.length - 1];
                            }
                            return;
                        }
                        if (!this._headAniInfo) {
                            this._headAniInfo = this._animationQueue.shift();
                        }
                        this._accTime += dt;
                        if (this._accTime > this._headAniInfo.delay) {
                            let aniInfo = this._headAniInfo;
                            this._headAniInfo = null;
                            this.setAnimation(0, aniInfo.animationName, aniInfo.loop);
                        }
                        return;
                    }
                    this._updateCache(dt);
                } else {
                    // @ts-ignore
                    if (cc.ENGINE_VERSION.startsWith('3.8')) {
                        const skeleton = this._skeleton;
                        const state = this._state;
                        if (skeleton) {
                            skeleton.update(dt);
                            if (state) {
                                state.update(dt);
                                state.apply(skeleton);
                            }
                        }
                    } else {
                        this._updateRealtime(dt);
                    }
                }
            }
        }
    }
}
SpinePreviewMode.spinePreviewMode();